
<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAtRange">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
         <el-date-picker
                  v-model="searchInfo.createdAtRange"
                  class="w-[380px]"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
       </el-form-item>
      
            <el-form-item label="商品名称" prop="name">
  <el-input v-model="searchInfo.name" placeholder="搜索条件" />
</el-form-item>
           
            <el-form-item label="商品类型" prop="productType">
  <el-select v-model="searchInfo.productType" clearable filterable placeholder="请选择" @clear="()=>{searchInfo.productType=undefined}" @change="handleSearchProductTypeChange">
    <el-option v-for="(item,key) in product_typeOptions" :key="key" :label="item.label" :value="item.value" />
  </el-select>
</el-form-item>
            <el-form-item label="状态" prop="status">
  <el-select v-model="searchInfo.status" clearable placeholder="请选择">
    <el-option key="true" label="上架" value="true"></el-option>
    <el-option key="false" label="下架" value="false"></el-option>
  </el-select>
</el-form-item>
           
        <template v-if="showAllQuery">
          <!-- 将需要控制显示状态的查询条件添加到此范围内 -->
        </template>

        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button link type="primary" icon="arrow-down" @click="showAllQuery=true" v-if="!showAllQuery">展开</el-button>
          <el-button link type="primary" icon="arrow-up" @click="showAllQuery=false" v-else>收起</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <el-button  type="primary" icon="plus" @click="openDialog()">新增</el-button>
            <el-button  icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="onDelete">删除</el-button>
            <ExportTemplate  template-id="wechatpay_Product" />
            <ExportExcel  template-id="wechatpay_Product" filterDeleted/>
            <ImportExcel  template-id="wechatpay_Product" @on-success="getTableData" />
        </div>
        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
        >
        <el-table-column type="selection" width="55" />
        
        <el-table-column sortable align="left" label="创建日期" prop="CreatedAt" width="180">
            <template #default="scope">{{ formatDate(scope.row.CreatedAt).split(' ')[0] }}</template>
        </el-table-column>
        
            <el-table-column align="left" label="商品名称" prop="name" width="120" />

            <el-table-column align="left" label="商品类型" prop="productType" width="120">
    <template #default="scope">
        {{ showDictLabel(product_typeOptions, scope.row.productType) }}
    </template>
</el-table-column>
            <el-table-column label="商品缩略图" prop="thumbnail" width="200">
    <template #default="scope">
      <el-image preview-teleported style="width: 100px; height: 100px" :src="getUrl(scope.row.thumbnail)" fit="cover"/>
    </template>
</el-table-column>


            <el-table-column align="left" label="状态" prop="status" width="120">
    <template #default="scope">{{ scope.row.status ? '上架' : '下架' }}</template>
</el-table-column>
        <el-table-column align="left" label="操作" fixed="right" min-width="240">
            <template #default="scope">
            <el-button  type="primary" link class="table-button" @click="getDetails(scope.row)"><el-icon style="margin-right: 5px"><InfoFilled /></el-icon>商品详情</el-button>
            <el-button  type="primary" link icon="edit" class="table-button" @click="updateProductFunc(scope.row)">编辑</el-button>
            <el-button   type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <el-drawer destroy-on-close size="800" v-model="dialogFormVisible" :show-close="false" :before-close="closeDialog">
       <template #header>
              <div class="flex justify-between items-center">
                <span class="text-lg">{{type==='create'?'新增':'编辑'}}</span>
                <div>
                  <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
                  <el-button @click="closeDialog">取 消</el-button>
                </div>
              </div>
            </template>

          <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px">
             <el-form-item label="商品名称:" prop="name">
    <el-input v-model="formData.name" :clearable="true" placeholder="请输入商品名称" />
</el-form-item>
             <el-form-item label="商品类型:" prop="productType">
    <el-select v-model="formData.productType" placeholder="请选择商品类型" style="width:100%" filterable :clearable="true" @change="handleProductTypeChange">
        <el-option v-for="(item,key) in product_typeOptions" :key="key" :label="item.label" :value="item.value" />
    </el-select>
</el-form-item>
             <el-form-item label="商品缩略图:" prop="thumbnail">
    <SelectImage
     v-model="formData.thumbnail"
     file-type="image"
    />
</el-form-item>
             <el-form-item label="商品图片:" prop="images">
    <SelectImage
     multiple
     v-model="formData.images"
     file-type="image"
     />
    <div v-if="formData.images && formData.images.length > 0" class="mt-2">
      <div class="text-sm text-gray-600 mb-2">已选择的图片：</div>
      <div class="flex flex-wrap gap-2">
        <div 
          v-for="(img, index) in formData.images" 
          :key="index"
          class="relative group"
        >
          <el-image 
            :src="getUrl(img)"
            style="width: 80px; height: 80px;"
            fit="cover"
            :preview-src-list="formData.images.map(item => getUrl(item))"
            :initial-index="index"
          />
          <div 
            class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity"
            @click="removeImage(index)"
            title="删除图片"
          >
            <el-icon :size="14">
              <Close />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
</el-form-item>
             <el-form-item label="商品详情:" prop="description">
    <RichEdit v-model="formData.description"/>
</el-form-item>
             <el-form-item label="商品属性:" prop="specification">
    <div class="product-attributes">
      <div class="mb-4">
        <div class="flex justify-between items-center mb-2">
          <span class="text-sm font-medium">商品属性配置</span>
          <el-button type="primary" size="small" icon="plus" @click="addAttribute">添加属性</el-button>
        </div>
        <div class="text-xs text-gray-500 mb-3">支持配置颜色、尺寸、款式、套餐等多种商品属性</div>
      </div>
      
      <div v-for="(attr, attrIndex) in productAttributes" :key="attrIndex" class="attribute-group mb-4 p-4 border border-gray-200 rounded">
        <div>
          <div class="flex items-center mb-3">
            <el-input 
              v-model="attr.name" 
              placeholder="属性名称（如：颜色、尺寸、款式等）" 
              style="width: 200px;" 
              class="mr-2"
            />
            <el-button type="danger" size="small" icon="delete" @click="removeAttribute(attrIndex)">删除属性</el-button>
          </div>
          
          <div class="attribute-values">
            <div class="flex justify-between items-center mb-2">
              <span class="text-sm text-gray-600">属性值配置：</span>
              <el-button type="primary" size="small" @click="addAttributeValue(attrIndex)">添加属性值</el-button>
            </div>
          
            <div v-for="(value, valueIndex) in attr.values" :key="valueIndex" class="flex items-center mb-2 gap-2">
              <el-input 
                v-model="value.name" 
                placeholder="属性值（如：红色、L码、经典款）" 
                style="width: 180px;" 
              />
              <div class="flex items-center gap-1">
                <el-input-number 
                  v-model="value.price" 
                  :precision="2" 
                  :min="0" 
                  placeholder="价格" 
                  style="width: 120px;" 
                />
                <span class="text-sm text-gray-500">元</span>
              </div>
              <div class="flex items-center gap-1">
                <el-input-number 
                  v-model="value.stock" 
                  :min="0" 
                  :max="10000"
                  placeholder="库存" 
                  style="width: 150px;" 
                />
                <span class="text-sm text-gray-500">件</span>
              </div>
              <el-input 
                v-model="value.sku" 
                placeholder="SKU编码" 
                style="width: 120px;" 
              />
              <el-button type="danger" size="small" icon="delete" @click="removeAttributeValue(attrIndex, valueIndex)" />
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="productAttributes.length === 0" class="text-center text-gray-400 py-8">
        <el-icon class="text-2xl mb-2"><Plus /></el-icon>
        <div>暂无商品属性，点击上方按钮添加</div>
      </div>
    </div>
</el-form-item>

             <el-form-item label="状态:" prop="status">
    <el-switch v-model="formData.status" active-color="#13ce66" inactive-color="#ff4949" active-text="上架" inactive-text="下架" clearable ></el-switch>
</el-form-item>
          </el-form>
    </el-drawer>

    <el-drawer destroy-on-close size="800" v-model="detailShow" :show-close="true" :before-close="closeDetailShow" title="查看">
            <el-descriptions :column="1" border>
                 <el-descriptions-item label="商品名称">
    {{ detailForm.name }}
</el-descriptions-item>
                 <el-descriptions-item label="商品类型">
    {{ showDictLabel(product_typeOptions, detailForm.productType) }}
</el-descriptions-item>
                 <el-descriptions-item label="商品缩略图">
    <el-image style="width: 50px; height: 50px" :preview-src-list="returnArrImg(detailForm.thumbnail)" :src="getUrl(detailForm.thumbnail)" fit="cover" />
</el-descriptions-item>
                 <el-descriptions-item label="商品图片">
    <el-image style="width: 50px; height: 50px; margin-right: 10px" :preview-src-list="returnArrImg(detailForm.images)" :initial-index="index" v-for="(item,index) in detailForm.images" :key="index" :src="getUrl(item)" fit="cover" />
</el-descriptions-item>
                 <el-descriptions-item label="商品详情">
    <RichView v-model="detailForm.description" />
</el-descriptions-item>
                 <el-descriptions-item label="商品属性">
    <div v-if="detailForm.specification && detailForm.specification.attributes && detailForm.specification.attributes.length > 0">
      <div v-for="(attr, index) in detailForm.specification.attributes" :key="index" class="mb-3">
        <div class="font-medium mb-1">{{ attr.name }}：</div>
        <div class="flex flex-wrap gap-2">
          <el-tag v-for="(value, vIndex) in attr.values" :key="vIndex" class="mr-1 mb-1">
            {{ value.name }} 
            <span v-if="value.price > 0">（¥{{ value.price }}）</span>
            <span v-if="value.stock >= 0">（库存：{{ value.stock }}）</span>
          </el-tag>
        </div>
      </div>
    </div>
    <div v-else class="text-gray-400">暂无商品属性</div>
</el-descriptions-item>

                 <el-descriptions-item label="状态">
    {{ detailForm.status ? '上架' : '下架' }}
</el-descriptions-item>
            </el-descriptions>
        </el-drawer>

  </div>
</template>

<script setup>
import {
  createProduct,
  deleteProduct,
  deleteProductByIds,
  updateProduct,
  findProduct,
  getProductList
} from '@/api/product'
import { getUrl } from '@/utils/image'
// 图片选择组件
import SelectImage from '@/components/selectImage/selectImage.vue'
// 富文本组件
import RichEdit from '@/components/richtext/rich-edit.vue'
import RichView from '@/components/richtext/rich-view.vue'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, returnArrImg, onDownloadFile } from '@/utils/format'
import { showDictLabel } from '@/utils/dictionary'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 导出组件
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
// 导入组件
import ImportExcel from '@/components/exportExcel/importExcel.vue'
// 导出模板组件
import ExportTemplate from '@/components/exportExcel/exportTemplate.vue'


defineOptions({
    name: 'Product'
})

// 提交按钮loading
const btnLoading = ref(false)

// 控制更多查询条件显示/隐藏状态
const showAllQuery = ref(false)

// 自动化生成的字典（可能为空）以及字段
const product_typeOptions = ref([])
const formData = ref({
            name: '',
            productType: undefined,
            thumbnail: "",
            images: [],
            description: '',
            specification: {},
            status: false,
        })

// 商品属性管理
const productAttributes = ref([])
// 添加属性
const addAttribute = () => {
  productAttributes.value.push({
    name: '',
    values: []
  })
}
// 移除属性
const removeAttribute = (attrIndex) => {
  productAttributes.value.splice(attrIndex, 1)
}
// 添加属性值
const addAttributeValue = (attrIndex) => {
  productAttributes.value[attrIndex].values.push({
    name: '',
    price: 0,
    stock: 0,
    sku: ''
  })
}
// 移除属性值
const removeAttributeValue = (attrIndex, valueIndex) => {
  productAttributes.value[attrIndex].values.splice(valueIndex, 1)
}
// 移除商品图片
const removeImage = (index) => {
  formData.value.images.splice(index, 1)
}

// 验证规则
const rule = reactive({
               name : [{
                   required: true,
                   message: '请输入商品名称',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               productType : [{
                   validator: (rule, value, callback) => {
                     if (value === 0 || value === null || value === undefined || value === '') {
                       callback(new Error('请选择商品类型'))
                     } else {
                       callback()
                     }
                   },
                   trigger: ['change', 'blur'],
              }
              ],
               thumbnail : [{
                   required: true,
                   message: '请上传商品缩略图',
                   trigger: ['input','blur'],
               },
              ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({
  productType: undefined
})
// 排序
const sortChange = ({ prop, order }) => {
  const sortMap = {
    CreatedAt:"CreatedAt",
    ID:"ID",
  }

  let sort = sortMap[prop]
  if(!sort){
   sort = prop.replace(/[A-Z]/g, match => `_${match.toLowerCase()}`)
  }

  searchInfo.value.sort = sort
  searchInfo.value.order = order
  getTableData()
}
// 重置
const onReset = () => {
  searchInfo.value = {
    productType: undefined
  }
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    if (searchInfo.value.status === ""){
        searchInfo.value.status=null
    }
    // 确保 productType 为数字类型
    if (searchInfo.value.productType && typeof searchInfo.value.productType === 'string') {
      searchInfo.value.productType = parseInt(searchInfo.value.productType)
    }
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getProductList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
    const dictData = await getDictFunc('product_type')
    // 将字典中的value转换为数字类型，以匹配formData.productType的数据类型
    product_typeOptions.value = dictData.map(item => ({
        ...item,
        value: parseInt(item.value) // 将字符串转换为数字
    }))
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 处理商品类型选择变化
const handleProductTypeChange = (value) => {
  // 确保选择的值为数字类型
  if (value !== null && value !== undefined) {
    formData.value.productType = typeof value === 'string' ? parseInt(value) : value
  } else {
    formData.value.productType = undefined
  }
}

// 处理搜索条件中商品类型选择变化
const handleSearchProductTypeChange = (value) => {
  // 确保选择的值为数字类型
  if (value !== null && value !== undefined) {
    searchInfo.value.productType = typeof value === 'string' ? parseInt(value) : value
  } else {
    searchInfo.value.productType = undefined
  }
}

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteProductFunc(row)
        })
    }

// 多选删除
const onDelete = async() => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
      const IDs = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          IDs.push(item.ID)
        })
      const res = await deleteProductByIds({ IDs })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        if (tableData.value.length === IDs.length && page.value > 1) {
          page.value--
        }
        getTableData()
      }
      })
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateProductFunc = async(row) => {
    const res = await findProduct({ ID: row.ID })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data
        
        // 确保 productType 为数字类型
        if (typeof formData.value.productType === 'string') {
          formData.value.productType = parseInt(formData.value.productType)
        }
        
        // 解析商品属性数据
        if (formData.value.specification && formData.value.specification.attributes) {
          productAttributes.value = formData.value.specification.attributes || []
        } else {
          productAttributes.value = []
        }
        
        dialogFormVisible.value = true
    }
}


// 删除行
const deleteProductFunc = async (row) => {
    const res = await deleteProduct({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        name: '',
        productType: undefined,
        price: 0,
        thumbnail: "",
        images: [],
        description: '',
        specification: {},
        stock: 0,
        status: false,
        }
    // 重置商品属性
    productAttributes.value = []
}
// 弹窗确定
const enterDialog = async () => {
     btnLoading.value = true
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return btnLoading.value = false
              
              // 确保 productType 为数字类型
              if (typeof formData.value.productType === 'string') {
                formData.value.productType = parseInt(formData.value.productType)
              }
              
              // 组装商品属性数据
              formData.value.specification = {
                attributes: productAttributes.value
              }
              
              let res
              switch (type.value) {
                case 'create':
                  res = await createProduct(formData.value)
                  break
                case 'update':
                  res = await updateProduct(formData.value)
                  break
                default:
                  res = await createProduct(formData.value)
                  break
              }
              btnLoading.value = false
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}

const detailForm = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findProduct({ ID: row.ID })
  if (res.code === 0) {
    detailForm.value = res.data
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailForm.value = {}
}


</script>

<style>

</style>
